<?php

declare(strict_types=1);

namespace app\common\model;

use app\common\facade\Target;
// use app\common\tool\pay\Pay;
//use app\common\tool\Target\Driver\Account;
use think\facade\Cache;
use think\facade\Event;
use app\common\facade\Pay;


class OrderRefund extends Base
{
    protected $name = 'order_refund';

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,mobile,photo');
    }

    public function order()
    {
        return $this->hasOne(Order::class, 'id', 'order_id');
    }
    public static function getTakeOverTableList($that, $param, $filed = '*', $count = 0)
    {
        try {
            foreach ($that as &$v) {
                $orderproducts = OrderProduct::where(['order_id' => $v['order_id']])->field('pid,product_title,num')->select()->toArray();
                $products = $orderproducts;
                foreach ($products as $item) {
                    $v->product .= $item['product_title'] . ' ' . '数量：' . $item['num'] . "\n";
                }
                $v->statusRaw = $v->getData('status');
            }
            return ['code' => 0, 'data' => $that, 'count' => $count];
        } catch (\Exception $e) {
            return [];
        }
    }
    public static function uploadLogistics($param, $user)
    {
        parent::startTrans();
        try {
            $find = parent::where(['id' => $param['id'], 'uid' => $user->id])->find();
            $find->express_id = $param['express_id'];
            $find->express_code = $param['express_code'];
            $find->status = 2;
            $find->save();
            parent::commit();
            return ['code' => 1, 'msg' => '上传物流信息成功'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 后台退款维权
     */
    public static function deliver($param, $admin)
    {

        try {
            $info = parent::with(['user', 'order'])->find($param['refund_id']);
            if ($info->isEmpty()) {
                return ['code' => -1, 'msg' => '未查询到相关退款申请'];
            }
            if ($param['status'] == 3) {
                if ($info->order->getData('pay_way') == 'wechat' || $info->order->getData('pay_way') == 'payment') {
                    $options = Pay::setDriver('WeChat')
                        ->refundBasic($info->order->sn, $info->order->sn, $info->money, $info->money)
                        ->refund();
                    if ($options['result_code'] == 'SUCCESS' && $options['return_code'] == 'SUCCESS' && $options['return_msg'] == 'OK') {
                        Order::where(['id' => $info->order_id])->update(['status' => -1, 'refund_time' => time()]);
                    } else {
                        return ['code' => -1, 'msg' => $options['err_code_des']];
                    }
                } else {
                    if ($info->order->getData('pay_way') == 'currency') {
                        Target::Account()
                            ->basics($info->order->uid, $info->order->getData('pay_way'), $info->order->real_amount, '商品退款', '+')
                            ->lock(false) //写入流水是否上锁，默认false，开启后会大幅降低性能，开启后必须配合事务使用
                            ->createNormal($info->order->uid);
                    }
                    if ($info->order->money > 0) {
                        $options = Pay::setDriver('WeChat')
                            ->refundBasic($info->order->sn, $info->order->sn, $info->order->money, $info->order->money)
                            ->refund();
                        if ($options['result_code'] == 'SUCCESS' && $options['return_code'] == 'SUCCESS' && $options['return_msg'] == 'OK') {
                            Order::where(['id' => $info->order_id])->update(['status' => -1, 'refund_time' => time()]);
                        } else {
                            return ['code' => -1, 'msg' => $options['err_code_des']];
                        }
                    }
                    if($info->order->lntegral>0){
                        Target::Account()
                            ->basics($info->order->uid, 'lntegral', $info->order->lntegral, '积分商品退款', '+')
                            ->lock(false) //写入流水是否上锁，默认false，开启后会大幅降低性能，开启后必须配合事务使用
                            ->createNormal($info->order->uid);
                    }
                    Order::where(['id' => $info->order_id])->update(['status' => -1, 'refund_time' => time()]);
                }
                $msg = $info->order->pay_way . '退款成功！操作人IP：【' . request()->ip() . '】 退款编号：' . $info->order->sn;
                $statusmsg = '退款成功！';
            } else {
                $info->reject_msg = $param['reject_msg'];
                $msg = $info->order->pay_way . '拒绝退款！操作人IP：【' . request()->ip() . '】 退款编号：' . $info->order->sn;
                $statusmsg = '拒绝退款！';
                $order = Order::where(['id' => $info->order_id])->find();
                Order::where(['id' => $info->order_id])->update(['status' => $order->refund_status]);
            }
            $info->status = $param['status'];
            $info->save();
            parent::commit();
            Logs::adds($msg, $admin->id, $admin->admin_name);
            return ['code' => 1, 'msg' => $statusmsg];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
